import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
    try {
        const formData = await request.formData();
        const audioFile = formData.get('audio_file') as File;
        
        if (!audioFile) {
            return NextResponse.json(
                { error: 'No audio file provided' },
                { status: 400 }
            );
        }

        // 创建新的FormData用于Azure API
        const azureFormData = new FormData();
        azureFormData.append('audio', audioFile, 'audio.wav');
        azureFormData.append('definition', JSON.stringify({"locales":["zh-CN"]}));
        
        const sttUrl = `https://eastus.api.cognitive.microsoft.com/speechtotext/transcriptions:transcribe?api-version=2024-11-15`;
        
        const response = await fetch(sttUrl, {
            method: 'POST',
            headers: {
                'Ocp-Apim-Subscription-Key': 'DH26AngBTSKnIzUMqSdh7l6levoYt53StgHDLTWrg5NpAlVAF50oJQQJ99BFACYeBjFXJ3w3AAAYACOG6flO'
            },
            body: azureFormData
        });

        if (!response.ok) {
            throw new Error(`Azure STT API error: ${response.status}`);
        }

        const result = await response.json();
        
        // 格式化返回数据以匹配原有的格式
        return NextResponse.json({
            data: {
                result: [{
                    text: result.combinedRecognizedPhrases?.[0]?.display || ''
                }]
            }
        });

    } catch (error) {
        console.error('STT API error:', error);
        return NextResponse.json(
            { error: 'Speech to text conversion failed' },
            { status: 500 }
        );
    }
}
